package com.clwl.supervise.superviseapp.service.pro;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clwl.supervise.superviseapp.entity.pro.*;
import com.clwl.supervise.superviseapp.entity.supervise.JgCheckResultTableSequence;
import com.clwl.supervise.superviseapp.mapper.pro.*;
import com.clwl.supervise.superviseapp.service.SequenceService;
import com.clwl.supervise.superviseapp.util.UserHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;


@Service
public class JgProCompanyDailyScoreService extends ServiceImpl<JgProCompanyDailyScoreMapper, JgProCompanyDailyScore> {

    @Autowired
    private JgProDailyInspectionItemMainMapper jgProDailyInspectionItemMainMapper;

    @Autowired
    private JgProDailyInspectionContentMainMapper jgProDailyInspectionContentMainMapper;

    @Autowired
    private JgProDailyInspectionMissingMainMapper jgProDailyInspectionMissingMainMapper;


    @Autowired
    private JgProCompanyDailyScoreInspectionItemMapper jgProCompanyDailyScoreInspectionItemMapper;

    @Autowired
    private JgProCompanyDailyScoreInspectionContentMapper jgProCompanyDailyScoreInspectionContentMapper;

    @Autowired
    private JgProCompanyDailyScoreInspectionMissingMapper jgProCompanyDailyScoreInspectionMissingMapper;
    @Autowired
    private JgProCompanyDailyScoreInspectionContentFileMapper contentFileMapper;
    @Resource
    private JgProRectificationMapper rectificationMapper;
    @Resource
    private JgProRectificationContentMapper rectificationContentMapper;

    @Resource
    private JgProInvestigationMapper jgProInvestigationMapper;
    @Resource
    private JgProInvestigationContentMapper jgProInvestigationContentMapper;

    @Resource
    private JgProCompanyDailyScoreMapper proCompanyDailyScoreMapper;
    @Resource
    private SequenceService sequenceService;

    @Transactional
    public boolean dailyScore(JgProCompanyDailyScore jgProCompanyDailyScore) {
        jgProCompanyDailyScore.setInspType("1");
        jgProCompanyDailyScore.setInspBose("0");
        jgProCompanyDailyScore.setIsSpecialItem("0");
        jgProCompanyDailyScore.setInspBoseName("食品生产监督检查要点表");
        //检查结果或检查情况为空，抛出异常
        if (StringUtils.isEmpty(jgProCompanyDailyScore.getCheckResult()) || StringUtils.isEmpty(jgProCompanyDailyScore.getHandleResult())) {
            throw new RuntimeException("'检查结果' 或 '检查情况' 不能为空! 请核实");
        }
        int result = 0;

//        jgProCompanyDailyScore.setStatus("1");
        if (jgProCompanyDailyScore.getId() == null) {
            //非计划
            QueryWrapper<JgProCompanyDailyScore> proCompanyDailyScoreQueryWrapper = new QueryWrapper<>();
            proCompanyDailyScoreQueryWrapper.eq("serial_num", "99");
            proCompanyDailyScoreQueryWrapper.eq("status", -1);
            proCompanyDailyScoreQueryWrapper.eq("company_id", jgProCompanyDailyScore.getCompanyId());
            proCompanyDailyScoreQueryWrapper.eq("year", DateUtil.year(new Date()));
            proCompanyDailyScoreQueryWrapper.orderByDesc("create_time");
            List<JgProCompanyDailyScore> proCompanyDailyScoreList = proCompanyDailyScoreMapper.selectList(proCompanyDailyScoreQueryWrapper);
            if (!proCompanyDailyScoreList.isEmpty()) {
                //已经生成过检查结果记录表了
                jgProCompanyDailyScore.setId(proCompanyDailyScoreList.get(0).getId());
                result = this.baseMapper.updateById(jgProCompanyDailyScore);
            } else {
//            jgProCompanyDailyScore.setCompanyId();  //如果是非计划专项检查 则  前端必传 企业ID 此参数
                jgProCompanyDailyScore.setSerialNum(99L);//99 代表非计划专项检查  不是日常计划检查
                jgProCompanyDailyScore.setYear(DateUtil.format(new Date(), "YYYY"));
                jgProCompanyDailyScore.setCreateTime(new Date());
                jgProCompanyDailyScore.setCreateBy(UserHelper.getUserInfo().getName());
                result = this.baseMapper.insert(jgProCompanyDailyScore);
            }
        } else {
            JgProCompanyDailyScore dailyScore = this.baseMapper.selectById(jgProCompanyDailyScore.getId());
            JgCheckResultTableSequence sequence = sequenceService.getResultTableSequence();
            Long resultRecordIndex = dailyScore.getResultRecordIndex() == null ? sequence.getTableIndex() : dailyScore.getResultRecordIndex();
            jgProCompanyDailyScore.setResultRecordIndex(resultRecordIndex);
            result = this.baseMapper.updateById(jgProCompanyDailyScore);
        }
        if (result > 0) {
            JSONArray ja = JSONArray.parseArray(jgProCompanyDailyScore.getContentSelect());
            HashMap map = new HashMap();
            map.put("daily_score_id", jgProCompanyDailyScore.getId());

            jgProCompanyDailyScoreInspectionItemMapper.deleteByMap(map);
            List<JgProDailyInspectionItemMain> itemList = jgProDailyInspectionItemMainMapper.selectList(new QueryWrapper<>());
            for (JgProDailyInspectionItemMain itemMain : itemList) {
                JgProCompanyDailyScoreInspectionItem item = new JgProCompanyDailyScoreInspectionItem();

                BeanUtil.copyProperties(itemMain, item, "id");
                item.setDailyScoreId(jgProCompanyDailyScore.getId());
                item.setItemId(itemMain.getId());
                jgProCompanyDailyScoreInspectionItemMapper.insert(item);
            }

            jgProCompanyDailyScoreInspectionContentMapper.deleteByMap(map);
            List<JgProDailyInspectionContentMain> contentList = jgProDailyInspectionContentMainMapper.selectList(new QueryWrapper<>());
            for (JgProDailyInspectionContentMain contentMain : contentList) {
                JgProCompanyDailyScoreInspectionContent content = new JgProCompanyDailyScoreInspectionContent();

                BeanUtil.copyProperties(contentMain, content, "id");
                content.setDailyScoreId(jgProCompanyDailyScore.getId());
                content.setContentId(contentMain.getId());
                content.setSelected("1");
                String filePicture = null;
                for (int j = 0; j < ja.size(); j++) {
                    // 获取当前索引的JSONObject
                    JSONObject jsonObject = ja.getJSONObject(j);
                    if (Long.valueOf(jsonObject.get("id").toString()).equals(contentMain.getId())) {
                        if (jsonObject.get("filePath") != null && !"".equals(String.valueOf(jsonObject.get("filePath")))) {
                            content.setFilePath(String.valueOf(jsonObject.get("filePath")));
                        }
                        if (jsonObject.get("filePicture") != null && !"".equals(String.valueOf(jsonObject.get("filePicture")))) {
                            filePicture = String.valueOf(jsonObject.get("filePicture"));
                        }
                        if (jsonObject.get("problemMsg") != null && !"".equals(String.valueOf(jsonObject.get("problemMsg")))) {
                            content.setProblemMsg(String.valueOf(jsonObject.get("problemMsg")));
                        }
                        content.setSelected(String.valueOf(jsonObject.get("selected")));
                        break;
                    } else {
                        content.setSelected("1");
                    }

                }

                jgProCompanyDailyScoreInspectionContentMapper.insert(content);
                //保存检查内容文件
                addProContentFile(content, filePicture);
            }

            jgProCompanyDailyScoreInspectionMissingMapper.deleteByMap(map);
            List<JgProDailyInspectionMissingMain> missingList = jgProDailyInspectionMissingMainMapper.selectList(new QueryWrapper<>());
            for (JgProDailyInspectionMissingMain missingMain : missingList) {
                JgProCompanyDailyScoreInspectionMissing missing = new JgProCompanyDailyScoreInspectionMissing();

                BeanUtil.copyProperties(missingMain, missing, "id");
                missing.setDailyScoreId(jgProCompanyDailyScore.getId());
                missing.setMissingId(missingMain.getId());
                missing.setSelected("0");
                for (int j = 0; j < ja.size(); j++) {
                    // 获取当前索引的JSONObject
                    JSONObject jsonObject = ja.getJSONObject(j);
                    if (jsonObject.get("missingSelectId") != null && Long.valueOf(jsonObject.get("missingSelectId").toString()).equals(missingMain.getId())) {
                        missing.setSelected("1");
                        break;
                    } else {
                        missing.setSelected("0");
                    }
                }

                jgProCompanyDailyScoreInspectionMissingMapper.insert(missing);
            }

            //责令整改
            if ("1".equals(jgProCompanyDailyScore.getStatus()) && "1".equals(jgProCompanyDailyScore.getHandleResult())) {
                this.saveRectification(this.baseMapper.selectById(jgProCompanyDailyScore.getId()), itemList, contentList, ja);
            }

            //调查处理
            if ("1".equals(jgProCompanyDailyScore.getStatus()) && "2".equals(jgProCompanyDailyScore.getHandleResult())) {
                this.saveRectification(this.baseMapper.selectById(jgProCompanyDailyScore.getId()), itemList, contentList, ja);
                this.saveInvestigation(this.baseMapper.selectById(jgProCompanyDailyScore.getId()), itemList, contentList, ja);
            }

            return true;
        } else {
            return false;
        }
    }

    private void addProContentFile(JgProCompanyDailyScoreInspectionContent content, String filePicture) {
        try {
            if (StringUtils.isNotEmpty(content.getFilePath()) && StringUtils.isNotEmpty(filePicture)) {
                JgProCompanyDailyScoreInspectionContentFile contentFile = new JgProCompanyDailyScoreInspectionContentFile();
                contentFile.setInspectionItemId(content.getInspectionItemId());
                contentFile.setInspectionContentId(content.getId());
                String mimeType = "image/jpeg"; // 根据实际文件类型调整
                filePicture = "data:" + mimeType + ";base64," + filePicture;
                contentFile.setFilePath(content.getFilePath());
                contentFile.setFilePicture(filePicture);
                contentFile.setCreateTime(new Date());
                contentFileMapper.insert(contentFile);
            }
        } catch (Exception e) {
            throw new RuntimeException("图内存过大！");
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void saveRectification(JgProCompanyDailyScore jgProCompanyDailyScore, List<JgProDailyInspectionItemMain> itemList, List<JgProDailyInspectionContentMain> contentList, JSONArray ja) {
        QueryWrapper<JgProRectificationEntity> rectificationQueryWrapper = new QueryWrapper<>();
        rectificationQueryWrapper.eq("delete_flag", "0");
        rectificationQueryWrapper.eq("check_type", "1");
        rectificationQueryWrapper.eq("check_id", jgProCompanyDailyScore.getId());
        rectificationQueryWrapper.orderByDesc("create_time");
        List<JgProRectificationEntity> rectificationList = rectificationMapper.selectList(rectificationQueryWrapper);
        JgProRectificationEntity rectification;
        if (!rectificationList.isEmpty()) {
            rectification = rectificationList.get(0);
        } else {
            rectification = new JgProRectificationEntity();
        }
        rectification.setCompanyId(jgProCompanyDailyScore.getCompanyId());
        rectification.setCheckId(jgProCompanyDailyScore.getId());
        rectification.setCheckPersonnel1(jgProCompanyDailyScore.getLawEnforcerId1());
        rectification.setCheckPersonnelName1(jgProCompanyDailyScore.getLawEnforcer1());
        rectification.setCheckPersonnel2(jgProCompanyDailyScore.getLawEnforcerId2());
        rectification.setCheckPersonnelName2(jgProCompanyDailyScore.getLawEnforcer2());
        rectification.setCheckType("1");
        rectification.setCheckStatus("1");
        rectification.setRectificationTimeLimit(DateUtil.format(jgProCompanyDailyScore.getRectificationTimeLimit(), "yyyy-MM-dd"));
        rectification.setCreateTime(new Date());
        rectification.setCreatorId(UserHelper.getUserId());
        rectification.setCreatorName(UserHelper.getUserInfo().getName());
        rectification.setDeleteFlag(0L);
        rectificationMapper.insert(rectification);

        //保存整改内容的初始信息
        for (JgProDailyInspectionContentMain contentMain : contentList) {
            for (int j = 0; j < ja.size(); j++) {
                // 获取当前索引的JSONObject
                JSONObject jsonObject = ja.getJSONObject(j);
                if (Long.valueOf(jsonObject.get("id").toString()).equals(contentMain.getId())) {
                    System.out.println(jsonObject.get("selected"));
                    if (!StringUtils.equals("0", jsonObject.getString("selected"))) {
                        continue;
                    }
                    JgProRectificationContentEntity rectificationContent = new JgProRectificationContentEntity();
                    rectificationContent.setRectificationId(rectification.getId());
                    rectificationContent.setCheckType("1");
                    rectificationContent.setCheckContentId(contentMain.getId());
                    rectificationContent.setCreateTime(new Date());
                    rectificationContent.setCreatorId(UserHelper.getUserId());
                    rectificationContent.setCreatorName(UserHelper.getUserInfo().getName());
                    rectificationContent.setDeleteFlag(0L);
                    for (JgProDailyInspectionItemMain itemMain : itemList) {
                        if (Objects.equals(itemMain.getId(), contentMain.getInspectionItemId())) {
                            rectificationContent.setSerialNum(itemMain.getSerialNumber());
                            rectificationContent.setStandardName(itemMain.getInspectionItemName());
                        }
                    }
                    rectificationContent.setContentNum(contentMain.getSerialNumber());
                    rectificationContent.setCheckContent(contentMain.getInspectionContent());
                    if (StringUtils.equals("0", jsonObject.getString("selected"))) {
                        rectificationContent.setSelection("2");
                    } else if (StringUtils.equals("-1", jsonObject.getString("selected"))) {
                        rectificationContent.setSelection("3");
                    } else {
                        rectificationContent.setSelection("1");
                    }
                    rectificationContent.setProblemContent(String.valueOf(jsonObject.get("problemMsg")));
                    rectificationContent.setProblemFile(String.valueOf(jsonObject.get("filePath")));
//            rectificationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
//            rectificationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
                    rectificationContent.setMissingItemContent(String.valueOf(jsonObject.get("problemMsg")));
                    rectificationContentMapper.insert(rectificationContent);

                }
            }
        }
    }

    private void saveInvestigation(JgProCompanyDailyScore jgProCompanyDailyScore, List<JgProDailyInspectionItemMain> itemList, List<JgProDailyInspectionContentMain> contentList, JSONArray ja) {
        QueryWrapper<JgProInvestigationEntity> rectificationQueryWrapper = new QueryWrapper<>();
        rectificationQueryWrapper.eq("delete_flag", "0");
        rectificationQueryWrapper.eq("check_type", "1");
        rectificationQueryWrapper.eq("check_id", jgProCompanyDailyScore.getId());
        rectificationQueryWrapper.orderByDesc("create_time");
        List<JgProInvestigationEntity> rectificationList = jgProInvestigationMapper.selectList(rectificationQueryWrapper);
        JgProInvestigationEntity investigation;
        if (!rectificationList.isEmpty()) {
            investigation = rectificationList.get(0);
        } else {
            investigation = new JgProInvestigationEntity();
        }
        investigation.setCompanyId(jgProCompanyDailyScore.getCompanyId());
        investigation.setCheckId(jgProCompanyDailyScore.getId());
        investigation.setCheckType("1");
        investigation.setCheckStatus("1");
        investigation.setCreateTime(new Date());
        investigation.setCreatorId(UserHelper.getUserId());
        investigation.setCreatorName(UserHelper.getUserInfo().getName());
        investigation.setDeleteFlag(0L);
        investigation.setCheckPersonnel(UserHelper.getUserId());//处理人员，谁检查的就是谁
        investigation.setCheckPersonnelName(UserHelper.getUserInfo().getName());
        jgProInvestigationMapper.insert(investigation);
        //保存整改内容的初始信息
        for (JgProDailyInspectionContentMain contentMain : contentList) {
            for (int j = 0; j < ja.size(); j++) {
                // 获取当前索引的JSONObject
                JSONObject jsonObject = ja.getJSONObject(j);
                if (Long.valueOf(jsonObject.get("id").toString()).equals(contentMain.getId())) {
                    if (!StringUtils.equals("0", jsonObject.getString("selected"))) {
                        continue;
                    }
                    JgProInvestigationContentEntity investigationContent = new JgProInvestigationContentEntity();
                    investigationContent.setInvestigationId(investigation.getId());
                    investigationContent.setCheckType("1");
                    investigationContent.setCheckContentId(contentMain.getId());
                    investigationContent.setCreateTime(new Date());
                    investigationContent.setCreatorId(UserHelper.getUserId());
                    investigationContent.setCreatorName(UserHelper.getUserInfo().getName());
                    investigationContent.setDeleteFlag(0L);
                    for (JgProDailyInspectionItemMain itemMain : itemList) {
                        if (Objects.equals(itemMain.getId(), contentMain.getInspectionItemId())) {
                            investigationContent.setSerialNum(itemMain.getSerialNumber());
                            investigationContent.setStandardName(itemMain.getInspectionItemName());
                        }
                    }

                    investigationContent.setContentNum(contentMain.getSerialNumber());
                    investigationContent.setCheckContent(contentMain.getInspectionContent());
                    if (StringUtils.equals("0", jsonObject.getString("selected"))) {
                        investigationContent.setSelection("2");
                    } else if (StringUtils.equals("-1", jsonObject.getString("selected"))) {
                        investigationContent.setSelection("3");
                    } else {
                        investigationContent.setSelection("1");
                    }
                    investigationContent.setProblemContent(String.valueOf(jsonObject.get("problemMsg")));
                    investigationContent.setProblemFile(String.valueOf(jsonObject.get("filePath")));
//            investigationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
                    investigationContent.setMissingItemContent(String.valueOf(jsonObject.get("problemMsg")));
//            investigationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
                    jgProInvestigationContentMapper.insert(investigationContent);

                }
            }
        }
    }

    /**
     * 生成结果记录表的序号
     *
     * @param checkId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String getResultTableCode(Long checkId, Long companyId) {
        if (checkId == null) {
            //非计划 需要事先生成一个检查单
            QueryWrapper<JgProCompanyDailyScore> proCompanyDailyScoreQueryWrapper = new QueryWrapper<>();
            proCompanyDailyScoreQueryWrapper.eq("serial_num", "99");
            proCompanyDailyScoreQueryWrapper.eq("status", -1);
            proCompanyDailyScoreQueryWrapper.eq("company_id", companyId);
            proCompanyDailyScoreQueryWrapper.eq("year", DateUtil.year(new Date()));
            proCompanyDailyScoreQueryWrapper.orderByDesc("create_time");
            List<JgProCompanyDailyScore> proCompanyDailyScoreList = proCompanyDailyScoreMapper.selectList(proCompanyDailyScoreQueryWrapper);
            JgProCompanyDailyScore companyDailyScore = null;
            if (proCompanyDailyScoreList.isEmpty()) {
                companyDailyScore = new JgProCompanyDailyScore();
                companyDailyScore.setInspType("1");
                companyDailyScore.setIsSpecialItem("0");
                companyDailyScore.setInspBose("0");
                companyDailyScore.setInspBoseName("食品生产监督检查要点表");
                companyDailyScore.setCompanyId(companyId);
                companyDailyScore.setYear(DateUtil.year(new Date()) + "");
                companyDailyScore.setSerialNum(99L);
                companyDailyScore.setDailyScore(0.0D);
                companyDailyScore.setStatus("-1");
                companyDailyScore.setCreateBy(UserHelper.getUserInfo().getName());
                companyDailyScore.setCreateTime(new Date());
                proCompanyDailyScoreMapper.insert(companyDailyScore);

            } else {
                companyDailyScore = proCompanyDailyScoreList.get(0);
            }
            checkId = companyDailyScore.getId();
        }
        JgProCompanyDailyScore proCompanyDailyScore = proCompanyDailyScoreMapper.selectById(checkId);
        if (proCompanyDailyScore.getResultRecordIndex() == null) {
            JgCheckResultTableSequence sequence = sequenceService.getResultTableSequence();
            proCompanyDailyScore.setResultRecordIndex(sequence.getTableIndex());
            proCompanyDailyScoreMapper.updateById(proCompanyDailyScore);
            return SequenceService.generatorProResultTableCode(sequence.getTableIndex());
        }
        return SequenceService.generatorProResultTableCode(proCompanyDailyScore.getResultRecordIndex());

    }
}
